#include "homepage.h"
#include "ui_homepage.h"
#include "globalval.h"

HomePage::HomePage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::HomePage)
{
    ui->setupUi(this);

    //实例化四个界面
    modbusWig = new ModbusWig;
    setWig = new SetWig;
    stm32 = new  Stm32;
    video = new Video;
    dataShow = new DataShow;
    ftpSocket = new QTcpSocket;

    //将四个界面依次添加到堆栈窗体
    ui->stackedWidget->addWidget(setWig);
    ui->stackedWidget->addWidget(dataShow);
    ui->stackedWidget->addWidget(modbusWig);
    ui->stackedWidget->addWidget(stm32);
    ui->stackedWidget->addWidget(video);

    tcpSocket = new QTcpSocket(this);

    // 创建定时器对象用来心跳检测
    timer = new QTimer(this);
    // 设置是否为一次性
    timer->setSingleShot(false);
    // 设置触发时间2s
    timer->setInterval(2000);
    connect(timer,&QTimer::timeout,
            this,&HomePage::timeoutSlot);

    //连接列表界面和堆栈窗体的信号
    QObject::connect(ui->listWidget, SIGNAL(currentRowChanged(int)),
                     ui->stackedWidget, SLOT(setCurrentIndex(int)));
    // setWig 窗体发来的信号，在home界面创建tcp连接
    QObject::connect(setWig, &SetWig::onDatagramRecv, this, &HomePage::onReceUdpMsg);
    QObject::connect(setWig, &SetWig::connectTcpServer, this, &HomePage::connectTcp);
    // tcp相关的信号
    QObject::connect(tcpSocket, &QTcpSocket::connected,this,&HomePage::connectedSlot);
    QObject::connect(tcpSocket, &QTcpSocket::disconnected,this,&HomePage::disconnectedSlot);
    QObject::connect(tcpSocket,&QTcpSocket::readyRead,this,&HomePage::readyReadSlot);
    // ftp 相关的信号
    QObject::connect(ftpSocket, &QTcpSocket::connected,this,&HomePage::ftpConnectSlot);
    QObject::connect(ftpSocket, &QTcpSocket::disconnected,this,&HomePage::ftpDisConnectSlot);
    QObject::connect(ftpSocket,&QTcpSocket::readyRead,this,&HomePage::ftpReadyReadSlot);

}

HomePage::~HomePage()
{
    delete ui;
}

void HomePage::connectMQTT(QString ip, int port)
{
    //mqtt相关
    GlobalVal::mqtt = new MqttHandler;
    GlobalVal::mqtt->setHost(QHostAddress(ip));
    GlobalVal::mqtt->setPort(port);
    GlobalVal::mqtt->connectToHost();
    // 接收mqtt消息的信号
    QObject::connect(GlobalVal::mqtt, SIGNAL(dataUpSignal(QByteArray)),
                     this, SLOT(dataUpSlot(QByteArray)));
}
// 接收udp服务器发来的tcp ip 和端口号
void HomePage::onReceUdpMsg(QJsonObject object)
{
    qDebug() << "onReceUdpMsg";
    QString type = object["type"].toString();
    if(type !=  "device search server")
        return;
    QString ip = object["ip"].toString();
    int port = object["port"].toInt();
    setWig->renderListWidgetItem(ip, port);
}

// 连接tcp的槽函数
void HomePage::connectTcp(QString ip, int port)
{
    if (tcpSocket->state() != QAbstractSocket::ConnectedState)
    {
        tcpSocket->connectToHost(ip, port);
        currentConnectIPAndPort = ip + ":" + QString::number(port);
    }
    else
    {
        QMessageBox::information(this, "提示", "已经有链接了");
    }
}
// 接收tcp传来的消息
void HomePage::readyReadSlot()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    while (tcpSocket->bytesAvailable() > 0) {
        QByteArray data = tcpSocket->readAll();
        QJsonDocument jsonDoc = QJsonDocument::fromJson(data);
        if (!jsonDoc.isNull()) {
            if (jsonDoc.isObject()) {
                QJsonObject jsonObject = jsonDoc.object();
                if (jsonObject.contains("type")) {
                    QJsonValue typeValue = jsonObject["type"];
                    if (typeValue.isDouble()) {
                        int type = static_cast<int>(typeValue.toDouble());
                        switch (type) { // 根据type的类型执行不同的操作
                        case 1: // 是否需要下发点表
                        {
                            if(jsonObject["up_config"].toBool())
                            {
                                sendPointTable();
                            }
                            else
                            {
                                QJsonObject dataj = jsonObject["data"].toObject();
                                QJsonObject mqttj = dataj["mqtt_config"].toObject();
                                QJsonObject update_config = dataj["update_config"].toObject();
                                qDebug() << mqttj;
                                GlobalVal::serverIp = mqttj["mqtt_addr"].toString();
                                connectMQTT(mqttj["mqtt_addr"].toString(), mqttj["mqtt_port"].toInt());
                                setWig->setReportMode(update_config["type"].toInt(),update_config["period"].toInt());
                                if(update_config["type"].toInt() == 0)
                                {
                                    setWig->setRefreshBtnShow(true);
                                }
                                else
                                {
                                    setWig->setRefreshBtnShow(false);
                                }
                                GlobalVal::isConnect = 1;
                                // 开启心跳检测
                                timer->start();
                            }
                            break;
                        }
                        case 2: // 发送点表
                        {
                            // 处理发送文件的情况
                            if(jsonObject["data"].toObject()["flag"].toString() == "start")
                                ftpSocket->connectToHost(socket->peerAddress(),jsonObject["port"].toInt());
                            else
                            {
                                QFile file("./node.json");
                                if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
                                    qDebug() << "无法打开文件:" << "./node.json";
                                    return;
                                }
                                QByteArray fileContent = file.readAll();
                                QJsonParseError jsonError;
                                QJsonDocument jsonDoc = QJsonDocument::fromJson(fileContent, &jsonError);

                                if (jsonError.error != QJsonParseError::NoError) {
                                    qDebug() << "JSON 解析错误:" << jsonError.errorString();
                                    return;
                                }

                                if (!jsonDoc.isObject()) {
                                    qDebug() << "JSON 文档不是一个对象";
                                    return;
                                }

                                QJsonObject jsonFile = jsonDoc.object();
                                QJsonObject dataj = jsonFile["mqtt_server"].toObject();
                                QJsonObject report = jsonFile["report"].toObject();
                                ftpSocket->disconnectFromHost();
                                qDebug() << dataj;
                                connectMQTT(dataj["addr"].toString(), dataj["port"].toInt());
                                GlobalVal::serverIp = dataj["addr"].toString();
                                setWig->setReportMode(report["type"].toInt(),report["period"].toInt());
                                if(report["type"].toInt() == 0)
                                {
                                    setWig->setRefreshBtnShow(true);
                                }
                                else
                                {
                                    setWig->setRefreshBtnShow(false);
                                }
                                GlobalVal::isConnect = 1;
                                // 开启心跳检测
                                timer->start();
                                file.close();
                            }

                            break;
                        }
                        case 3: // 心跳检测
                            isAlive = 1;
                            break;
                        default:
                            // 处理未知type的情况
                            qDebug() << "Unknown type received:" << type;
                            break;
                        }
                    }
                }
            }
        } else {
            qDebug() << "Invalid JSON received";
        }
    }
}
// 客户端连接到服务器之后发送一个type：1 询问服务器是不是需要点表
void HomePage::connectedSlot()
{
    QString text(currentConnectIPAndPort);
    ui->connectLabel->setText(text.append(" 已连接"));

    // 创建 JSON 对象
    QJsonObject jsonObject;
    jsonObject["type"] = 1;

    // 序列化 JSON 对象
    QJsonDocument jsonDoc(jsonObject);
    QByteArray jsonByteArray = jsonDoc.toJson(QJsonDocument::Compact);
    qDebug() << "send";
    tcpSocket->write(jsonByteArray);
}
// 发送点表数据给ftp服务器
void HomePage::sendPointTable()
{

    QFile file("node.json");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "open err" << file.errorString();
        return;
    }

    // 读取文件内容到QByteArray
    QByteArray fileData = file.readAll();
    file.close();

    // 获取文件长度
    qint64 fileLen = fileData.size();

    // 构造JSON对象
    QJsonObject jsonObject;
    jsonObject["type"] = 2;
    QJsonObject dataObject;
    dataObject["flag"] = "start";
    dataObject["file_name"] = "node.json";
    dataObject["file_len"] = fileLen;
    jsonObject["data"] = dataObject;

    // 将JSON对象序列化为字符串
    QJsonDocument jsonDoc(jsonObject);
    QByteArray jsonByteArray = jsonDoc.toJson(QJsonDocument::Compact);

    // 发送JSON字符串到TCP服务器
    tcpSocket->write(jsonByteArray);

}

void HomePage::disconnectedSlot()
{
    ui->connectLabel->setText("未连接");
}
// 发送点表文件给服务器
void HomePage::uploadPointTableFile()
{
    QFile file("node.json");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "open err" << file.errorString();
        return;
    }
    // 读取文件内容到QByteArray
    QByteArray fileData = file.readAll();
    file.close();
    ftpSocket->write(fileData);
    sendStopFrame();
}
// 文件发送完之后发送给stop
void HomePage::sendStopFrame()
{
    QJsonObject stopDataObj;
    stopDataObj["flag"] = "stop";
    QJsonObject rootObj;
    rootObj["type"] = 2;
    rootObj["data"] = stopDataObj;
    QJsonDocument stopDoc(rootObj);
    qDebug() << stopDoc;
    QByteArray stopFrame = stopDoc.toJson(QJsonDocument::Compact);
    tcpSocket->write(stopFrame);
}
// 心跳检测槽函数
void HomePage::timeoutSlot()
{
    if(isAlive == 1)
    {
        QJsonObject aliveJson;
        aliveJson["type"] = 3;
        QJsonDocument aliveDoc(aliveJson);
        QByteArray aliveFrame = aliveDoc.toJson();
        tcpSocket->write(aliveFrame);
        isAlive = 0;
    }
    else
    {
        GlobalVal::isConnect = 1;
        QMessageBox::warning(this, "警告", "服务器断开连接");
        ui->connectLabel->setText("未连接");
        timer->stop();
    }
}
// 获取mqtt发来的设备数据并发送给具体的界面
void HomePage::dataUpSlot(QByteArray data)
{
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data);
    if (!jsonDoc.isNull()) {
        if (jsonDoc.isObject()) {
            QJsonObject jsonObject = jsonDoc.object();
            dataShow->dataShowToUi(jsonObject);
            stm32->switchCtlToUi(jsonObject);
            modbusWig->switchCtlToUi(jsonObject);
        }
    } else {
        qDebug() << "Invalid JSON data";
    }
}

void HomePage::ftpConnectSlot()
{
    qDebug() << "ftpConnectSlot";
    uploadPointTableFile();
}

void HomePage::ftpDisConnectSlot()
{
    qDebug() << "FTP DISCONNECT";
}

void HomePage::ftpReadyReadSlot()
{
    qDebug() << "ftpreadyReadSlot";
}
